import type { CardQueryParams, CardList, CardItem, SearchConfigDealItem } from '/@/api/general/model/cardModel';
import { defineComponent, reactive, ref, toRaw, unref } from 'vue';
import { useGeneralGameHooks } from '/@/views/general/hooks/useConfigs';
import { useGo } from '/@/hooks/web/usePage';
import { useElementSize } from '@vueuse/core';
import { appShareUsing, getAppParameters } from '/@/utils/appInteractive';
import { awaitWrap, filterNullAttributes, judgeSystem } from '/@/utils';
import { CardListApi } from '/@/api/general/card';
import Title from '/@/views/general/components/Title';
import { Empty, List, Image, Field, Button } from 'vant';
import { Icon } from '/@/components/Icon';
import BaseSearchPopup from '/@/views/general/components/CardSearch/BaseSearchPopup';
import SeriesSearchPopup from '/@/views/general/components/CardSearch/SeriesSearchPopup';
import CurrentAttrPopup from '/@/views/general/components/CardSearch/CurrentAttrPopup';
import SearchHistory from '/@/views/general/components/SearchHistory';

import('./index.less');

export default defineComponent({
  name: 'GeneralCardPage',
  props: {
    gameId: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    getAppParameters(); // 需要重新获取一下token 因为是在app使用

    // 设置分享参数
    appShareUsing({
      title: '弈仙牌',
      content: '弈仙牌',
      image: 'https://pic.iyingdi.com/yingdiimg/gadgets/yixian/%E5%BC%88%E4%BB%99%E7%89%8CLOGO.png',
      url: window.location.href,
    });

    const go = useGo();

    const { getGameConfig, getSearchConfig, gameConfigData } = useGeneralGameHooks(); // gameConfigData
    getGameConfig({ game_id: props.gameId });
    getSearchConfig({ game_id: props.gameId });

    const queryState = reactive<CardQueryParams>({
      game_id: props.gameId,
      page: 1,
      size: 20,
      name: '',
      series_ids: [],
    });

    // 数据获取
    const listLoading = ref(false); // 是否处于加载状态 默认不处于，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<CardList>({
      total_page: 0,
      rows: [],
    });

    const getList = async (isRefresh: boolean) => {
      if (isRefresh) {
        queryState.page = 1;
        listData.rows = [];
        listData.total_page = 0;
        listLoading.value = true;
      }
      const params: CardQueryParams = filterNullAttributes(queryState, []);
      const [error, result] = await awaitWrap(CardListApi(toRaw(params)));
      if (error || !result) {
        return;
      }
      if (queryState.page === 1) {
        listFinished.value = false;
        !result.rows.length ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      listLoading.value = false;
      if (result.total_page === queryState.page || !result.total_page) {
        listFinished.value = true;
        return;
      }
      queryState.page += 1;
    };

    const CardItem = ({ card }: { card: CardItem }) => {
      let AbbrPrice: VueNode = null;
      const { series_cn_abbr, price } = card;
      if (series_cn_abbr || price) {
        const Abbr = (
          <span class={'w-[50%] px-sm text-center van-ellipsis border-r border-gray-300'}>{series_cn_abbr || '-'}</span>
        );
        const Price = price ? (
          <span class={'flex-1 px-sm text-center van-ellipsis'}>¥{price / 100}</span>
        ) : (
          <span class={'flex-1 px-sm text-center van-ellipsis'}>¥-</span>
        );
        AbbrPrice = (
          <div class={'flex text-[16px] pb-sm text-gray-600'}>
            {Abbr}
            {Price}
          </div>
        );
      }
      return (
        <li
          class={'card-item'}
          onClick={() => {
            go(`/generalcard/${props.gameId}/${card.id}`);
          }}
        >
          <div class={'image'}>
            <Image src={card.img} class={'w-full h-full'} lazyLoad />
          </div>
          <div class={'name-box'}>
            <div class={'name-content van-ellipsis text-xs px-sm'}>{card.name}</div>
            {AbbrPrice}
          </div>
        </li>
      );
    };

    // 适配安卓键盘
    const bottomSearchClass = ref('');
    const fieldFocusClick = () => {
      searchHistoryState.value = true;
      console.log(judgeSystem());
      if (judgeSystem() === 'android') {
        bottomSearchClass.value = 'android';
        return false;
      }
      bottomSearchClass.value = '';
    };
    const fieldBlurClick = () => {
      bottomSearchClass.value = '';
      setTimeout(() => {
        searchHistoryState.value = false;
      });
    };
    const searchFieldSlot = {
      button: () => {
        return (
          <Button
            type={'primary'}
            size={'small'}
            onClick={() => {
              getList(true);
            }}
            color={'#000'}
          >
            搜索
          </Button>
        );
      },
    };

    // 筛选Popup
    const searchState = ref(false);
    const seriesPopupState = ref(false);
    const currentPopupState = ref(false);
    // 打开其他条件筛选
    const filterClick = () => {
      searchState.value = true;
    };
    // 打开系列筛选
    const seriesPopupClick = () => {
      seriesPopupState.value = true;
    };
    // 打开其他动态筛选浮层
    const currentAttrRef = ref<SearchConfigDealItem>({} as SearchConfigDealItem);
    const currentPopupClick = (currentAttr: SearchConfigDealItem) => {
      currentAttrRef.value = currentAttr;
      currentPopupState.value = true;
    };

    // 搜索记录
    const searchHistoryState = ref(false);
    const bottomAreaRef = ref();
    const { height } = useElementSize(bottomAreaRef);
    const setQueryName = (name: string) => {
      console.log(name);
      queryState.name = name;
      getList(true);
    };

    return () => (
      <div class={'general-card-page'}>
        <Title title={gameConfigData.game_name} logo={gameConfigData.game_logo} />
        <div class={'card-list-container'}>
          {unref(listEmpty) ? (
            <Empty>未找到相关卡牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多卡牌'}
              onLoad={getList}
              offset={0}
            >
              <ul class='card-list flex flex-wrap'>
                {listData.rows.map((card) => {
                  return <CardItem card={card} />;
                })}
              </ul>
            </List>
          )}
        </div>
        <div class={`bottom-area flex ${unref(bottomSearchClass)}`} ref={bottomAreaRef}>
          <SearchHistory
            gameId={props.gameId}
            queryParams={queryState}
            v-model={[searchHistoryState.value, 'show']}
            areaHeight={height.value}
            onSetQueryParamsName={setQueryName}
          />
          <div class={'bottom-search flex items-center'}>
            <div class={'input-box'}>
              <Field
                v-model={[queryState.name]}
                placeholder='卡牌名称或规则'
                leftIcon={'search'}
                v-slots={searchFieldSlot}
                clearable
                onFocus={fieldFocusClick}
                onBlur={fieldBlurClick}
              />
            </div>
            <div class='svg-button filter text-center flex-1' onClick={filterClick}>
              <Icon icon={'single-filter|svg'} size={30} />
            </div>
          </div>
        </div>
        <BaseSearchPopup
          v-model={[searchState.value, 'show']}
          queryState={queryState}
          onPageRefresh={() => {
            getList(true);
          }}
          onOpenSeriesPopup={seriesPopupClick}
          onOpenCurrentAttrsPopup={currentPopupClick}
        />
        <SeriesSearchPopup
          v-model={[seriesPopupState.value, 'show']}
          queryState={queryState}
          gameId={props.gameId}
          onPageRefresh={() => {
            getList(true);
          }}
        />
        <CurrentAttrPopup
          v-model={[currentPopupState.value, 'show']}
          queryState={queryState}
          currentAttrs={currentAttrRef}
          onPageRefresh={() => {
            getList(true);
          }}
        />
      </div>
    );
  },
});
